<template>
  <div class="dashboard">
    <header class="header">
      <div class="logo">
        <img src="@/assets/svgs/logo.svg" alt="Logo" class="logo-image">
        <span class="title">智慧教室</span>
      </div>
      <div class="user-info" @click="toggleDropdown">
        <img class="avatar" :src="userInfo?.avatarUrl" alt="User Avatar">
        <span class="username22">{{ userInfo?.nick_name }}</span>
        <img class="dropdown-arrow" src="@/assets/svgs/downnarrow.svg" alt="Dropdown Arrow">
        <div v-if="dropdownVisible" class="dropdown-menu">
          <p @click="$router.push('/teacher/information')">个人信息</p>
          <p @click="$router.push('/login')">退出登录</p>
        </div>
      </div>
    </header>
    <div class="grid">
      <div class="grid-item" key="1" @click="$router.push('/ai')"
        style="background-color: #13227a; color: white;font-size: larger; display: flex; flex-direction: column; justify-content: center; align-items: center;">
        <div class="icon-title" style="display: flex; align-items: center; height: 50%;">
          <img class="icon large-icon" src="@/assets/svgs/robot2.svg" alt="Icon">
          <span>AI助手</span>
        </div>
        <p style="font-size: medium;">智能辅助教学，提升课堂效率</p>
      </div>

      <div class="grid-item" key="2" @click="navigateTo('mycourse')"
        style="display: flex; flex-direction: column; justify-content: center; align-items: center;">
        <img class="icon large-icon" src="@/assets/svgs/course.svg" alt="Icon">
        <span>我的课程</span>
      </div>
      <div class="grid-item" key="3" @click="$router.push('/student/chat')"
        style="display: flex; flex-direction: column; justify-content: center; align-items: center;">
        <img class="icon large-icon" src="@/assets/svgs/AIBot.svg" alt="Icon">
        <span>AIGC智能聊天室</span>
      </div>

      <div class="grid-item" key="4" @click="navigateTo('homework')"
        style="background-color: white; color: black; display: flex; flex-direction: column;">
        <div class="icon-title" style="display: flex; align-items: center; height: 25%;">
          <img class="icon small-icon" src="@/assets/svgs/signin.svg" alt="Icon">
          <span>AIGC智能作业</span>
        </div>
        <div class="stats-container">
          <div class="stats-item">
            <span class="number">{{ homeworkStats.completed }}</span>
            <span class="label">已截止</span>
          </div>
          <div class="stats-item">
            <span class="number" style="color: gray;">{{ homeworkStats.total }}</span>
            <span class="label">总数</span>
          </div>
        </div>
      </div>

      <div class="grid-item" key="5" @click="$router.push('/student/signin/index')"
        style="display: flex; flex-direction: column;">
        <div class="icon-title" style="display: flex; align-items: center; height: 25%;">
          <img class="icon small-icon" src="@/assets/svgs/record.svg" alt="Icon">
          <span>签到点名</span>
        </div>
        <div class="stats-container">
          <div class="stats-item">
            <span class="number">{{ totalSigned }}</span>
            <span class="label">已完成</span>
          </div>
          <div class="stats-item">
            <span class="number" style="color: gray;">{{ totalSign }}</span>
            <span class="label">总数</span>
          </div>
        </div>
      </div>

      <div class="grid-item" key="6" @click="navigateTo('studentfeedback')"
        style="display: flex; flex-direction: column;">
        <div class="icon-title" style="display: flex; align-items: center; height: 25%;">
          <img class="icon small-icon" src="@/assets/svgs/feedback.svg" alt="Icon">
          <span>课堂质量实时反馈</span>
        </div>
        <div class="stats-container">
          <div class="stats-item">
            <span class="number">{{ feedbackStats.completed }}</span>
            <span class="label">已填写</span>
          </div>
          <div class="stats-item">
            <span class="number" style="color: gray;">{{ feedbackStats.total }}</span>
            <span class="label">总数</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, useId, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { getStudentAllSign } from '@/api/sign'
import { useUserIdStore } from '@/stores/userId';
import { useCourseManageIdStore } from '@/stores/courseManageId';
import { informationService } from '@/api/personnal-information';
import { getStudentHomeworkService } from '@/api/homework';
import { surveyListService, getFeedbackStats } from '@/api/feedback';
import { getStudentCourseList } from '@/api/course';

// 定义响应式数据

const userInfo = ref(null);

const fetchUserInfo = async () => {
  try {
    const result = await informationService();
    const userData = result.data; // 假设后端返回的数据结构是 { data: SysUser }
    userInfo.value = {
      userId: userData.userId,
      avatarUrl: userData.avatar,
      user_name: userData.userName,
      nick_name: userData.nickName
    };
  } catch (error) {
    console.error('获取用户信息失败:', result.message);
  }
};
fetchUserInfo();
const currentTime = ref('');
const formattedTime = ref('');
const dropdownVisible = ref(false);
const totalSigned = ref('');
const totalSign = ref('');
const router = useRouter();
const route = useRoute();
const userIdStore = useUserIdStore();
const courseManageIdStore = useCourseManageIdStore();
const getSign = async () => {
  const userId = userIdStore.userId;
  const courseManageId = courseManageIdStore.courseManageId;
  console.log("注意userId,courseManageId：",userId,courseManageId);
  try {
    const response = await getStudentAllSign(userId, courseManageId);
    console.log("注意这个response",response);
    totalSigned.value = response.totalSigned;
    totalSign.value = response.totalSign;
    console.log("totalSigned,totalSign",totalSigned.value,totalSign.value);
    }
    catch (error) {
      console.error('Error fetching sign data:', error);
    }
   
};
getSign();
const toggleDropdown = () => {
  dropdownVisible.value = !dropdownVisible.value;
};

const navigateTo = (page) => {
  if (page === 'profile') {
    router.push('/profile');
  } else if (page === 'logout') {
    router.push('/login');
  } else if (page === 'home') {
    router.push('/home');
  } else if (page === 'homework') {
    router.push('/student/homework/card');
  } else if (page === 'studentfeedback') {
    router.push('/student/feedback/card');
  } else if (page === 'mycourse') {
    router.push('/student/mycourse');
  }
};

// 添加统计数据的响应式变量
const homeworkStats = ref({
  total: 0,
  completed: 0
});

const feedbackStats = ref({
  total: 0,
  completed: 0
});

// 获取作业统计数据
const fetchHomeworkStats = async () => {
  try {
    const coursesResponse = await getStudentCourseList();
    if (coursesResponse.code === 0 && coursesResponse.data) {
      let totalHomeworks = 0;
      let completedHomeworks = 0;

      // 获取所有课程的作业
      for (const course of coursesResponse.data) {
        try {
          const response = await getStudentHomeworkService(course.courseManageId);
          if (response.code === 0 && response.data) {
            const homeworks = response.data;
            totalHomeworks += homeworks.length;
            // 统计已提交和已批改的作业
            completedHomeworks += homeworks.filter(hw => 
              hw.state === '已截止' 
            ).length;
          }
        } catch (error) {
          console.error(`获取课程 ${course.courseManageId} 的作业失败:`, error);
        }
      }

      homeworkStats.value = {
        total: totalHomeworks,
        completed: completedHomeworks
      };
    }
  } catch (error) {
    console.error('获取作业统计失败:', error);
  }
};

// 获取问卷统计数据
const fetchFeedbackStats = async () => {
  try {
    const result = await getFeedbackStats();
    console.log('问卷统计数据:', result);

    if (result.code === 0) {
      feedbackStats.value = {
        total: result.data.total || 0,
        completed: result.data.completed || 0
      };
      console.log('更新后的统计数据:', feedbackStats.value);
    } else {
      console.error('获取统计数据失败:', result.message);
    }
  } catch (error) {
    console.error('获取问卷统计失败:', error);
  }
};

// 监听路由变化，当从问卷页面返回时刷新统计数据
watch(
  () => route.query,
  (newQuery) => {
    if (newQuery.refresh) {
      fetchFeedbackStats();
    }
  }
);

// 在组件挂载时获取统计数据
onMounted(async () => {
  await Promise.all([
    fetchHomeworkStats(),
    fetchFeedbackStats()
  ]);
});

// onMounted(() => {
//   setInterval(() => {
//     const now = new Date();
//     const dateString = now.toLocaleDateString();
//     const timeString = now.toLocaleTimeString();
//     if (classStatus.value === '没有上课') {
//       formattedTime.value = `${dateString} ${timeString}`;
//     } else {
//       formattedTime.value = `${classStatus.value} - ${dateString} ${timeString}`;
//     }
//   }, 1000);
// });
</script>

<style>
.dashboard {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f0f0f0;
  /* 浅灰色背景 */
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #13227a;
  color: white;
  padding: 10px 20px;
}

.logo {
  display: flex;
  align-items: center;
  color: white;
  font-size: 18px;
  font-weight: bold;
}

.logo-image {
  width: 24px;
  height: 24px;
  margin-right: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  position: relative;
  cursor: pointer;
}

.avatar {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 10px;
}

.dropdown-arrow {
  width: 16px;
  height: 16px;
  margin-left: 5px;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: white;
  color: black;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 10px;
  z-index: 1000;
}

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  padding: 20px;
  flex: 1;
  width: 1000px;
  /* 调整总宽度 */
  margin: 50px auto;
  /* 增加上下边距，保持水平居中 */
  justify-content: center;
  /* 网格水平居中 */
  align-content: center;
  /* 网格垂直居中 */
}

.grid-item {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  /* 靠左对齐 */
  align-items: center;
  /* 靠中对齐 */
  background-color: white;
  border-radius: 8px;
  width: 100%;
  /* 改为相对宽度 */
  height: 180px;
  cursor: pointer;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.completion-status {
  text-align: center;
  /* 居中对齐 */
}

.icon-title {
  display: flex;
  align-items: center;
}

.large-icon {
  width: 60px;
  /* 增大图标大小 */
  height: 60px;
  /* 增大图标大小 */
}

.small-icon {
  width: 30px;
  /* 减小图标大小 */
  height: 30px;
  /* 减小图标大小 */
}

.number {
  font-size: 32px;
  /* 增大数字部分的大小 */
  color: #13227a;
  /* 保持颜色 */
}

.text {
  color: gray;
  /* 改为灰色 */
}

.stats {
  display: flex;
  justify-content: space-between;
  /* 左右分布 */
  width: 100%;
  padding: 10px;
  position: absolute;
  bottom: 10px;
  /* 靠近底部 */
}

.stats .left {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  /* 右对齐 */
  margin-top: auto;
  /* 使其靠近下半部分 */
  margin-right: 20px;
  /* 增加右侧边距以增加距离 */
}

.stats .right {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  /* 左对齐 */
  margin-top: auto;
  /* 使其靠近下半部分 */
}

/* 添加新的样式 */
.stats-container {
  height: 75%;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 40px;
}

.stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stats-item .number {
  font-size: 32px;
  color: #13227a;
  margin-bottom: 8px;
  line-height: 1;  /* 确保数字的行高一致 */
}

.stats-item .label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}
</style>
